package com.shop.loan.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.channel.ciwei.CwAESUtil;
import com.shop.loan.mapper.ArNotifyLogMybatisMapper;
import com.shop.loan.mapper.UserByMybatisMapper;
import com.shop.loan.model.common.Code;
import com.shop.loan.model.common.ResResultByCiWei;
import com.shop.loan.model.entity.ArNotifyLogMybatisWithBLOBs;
import com.shop.loan.model.entity.LoanOrderByMybatis;
import com.shop.loan.model.entity.UserByMybatis;
import com.shop.loan.model.enums.OrderStatus;
import com.shop.loan.model.enums.UserStatus;
import com.shop.loan.model.vo.CiWeiParamVo;
import com.shop.loan.service.AsyncService;
import com.shop.loan.service.CiWeiService;
import com.shop.loan.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class CiWeiServiceImpl implements CiWeiService {

    @Value("${api.ciwei.channelId}")
    private Long channelId;

    @Value("${api.ciwei.callbackUrl}")
    private String callbackUrl;

    @Value("${api.ciwei.appId}")
    private String appId;

    @Value("${api.ciwei.appKey}")
    private String appKey;

    @Value("${sys.urlByH5}")
    private String urlByH5;

    @Lazy
    @Resource
    UserService userService;

    @Resource
    ArNotifyLogMybatisMapper arNotifyLogMybatisMapper;

    @Resource
    AsyncService asyncService;

    @Resource
    UserByMybatisMapper userByMybatisMapper;

    public static String platform = "ciwei";

    @Override
    public ResResultByCiWei login(CiWeiParamVo ciWeiParamVo) {
        String desStr = CwAESUtil.decryptCBC(ciWeiParamVo.getBizData(), appKey);
        if (!StringUtils.hasLength(desStr)) {
            return new ResResultByCiWei(Code.SIGN_ERROR);
        }
        JSONObject dataJs = JSON.parseObject(desStr);
        if (dataJs == null || !dataJs.containsKey("mobile")) {
            return new ResResultByCiWei(Code.PARAM_REJECT);
        }
        String mobile = dataJs.getString("mobile");

        int code = 200;
        UserByMybatis userByMybatis = userByMybatisMapper.selectByMobile(mobile);
        if (userByMybatis != null && userByMybatis.getId() != null) {
            if (userByMybatis.getChannelId().intValue() != channelId) {
                code = 100;
            }
            if (!userByMybatis.getMachineStatus() || userByMybatis.getUserStatus().intValue() == UserStatus.black.getType()) {
                code = 101;
            }
        }
        ResResultByCiWei resResult = userService.loginByCiWei(mobile, channelId, platform, null);
        JSONObject urlJs = new JSONObject();
        urlJs.put("url", getUrlByToken(resResult.getData().toString()));
        resResult.setData(urlJs);
        resResult.setCode(code);
        if (code == 200) {
            resResult.setMessage("成功");
        } else if (code == 100) {
            resResult.setMessage("信息撞库");
        } else {
            resResult.setMessage("审核拒绝");
        }
        return resResult;
    }


    @Override
    public ResResultByCiWei notifyOrderStatus(LoanOrderByMybatis loanOrderByMybatis, UserByMybatis userByMybatis) {
        if (loanOrderByMybatis == null || userByMybatis == null) {
            return new ResResultByCiWei(Code.PARAM_INVALID);
        }
        if (channelId == 0) {
            return new ResResultByCiWei(Code.PARAM_INVALID);
        }
//        业务状态：
//        1= 信息撞库
//        2=未申请
//        3=发起申请
//        4=审核通过，等待放款
//        5=审核拒绝
//        6=已放款
//        7=拒绝放款
        JSONObject bizDataJs = new JSONObject();
        bizDataJs.put("appId", appId);
//        bizDataJs.put("mobile", "19000000000");
        bizDataJs.put("mobile", userByMybatis.getMobile());
        bizDataJs.put("bizStatus", getBizStatus(loanOrderByMybatis.getStatus()));
        bizDataJs.put("money", loanOrderByMybatis.getMoney());

        JSONObject paramJs = new JSONObject();
        paramJs.put("appId", appId);
        paramJs.put("bizData", CwAESUtil.encryptCBC(bizDataJs.toJSONString(), appKey));

        //插入推送记录表
        ArNotifyLogMybatisWithBLOBs arNotifyLogMybatis = new ArNotifyLogMybatisWithBLOBs();
        arNotifyLogMybatis.setReqParam(paramJs.toJSONString());
        arNotifyLogMybatis.setCreateTime(new Date());
        arNotifyLogMybatis.setStatus(false);
        arNotifyLogMybatis.setUrl(callbackUrl);
        arNotifyLogMybatisMapper.insertSelective(arNotifyLogMybatis);

        asyncService.sendNotify(arNotifyLogMybatis, null);
        return new ResResultByCiWei(Code.SUCCESS);
    }

    public String getUrlByToken(String token) {
        return urlByH5 + "?token=" + token;
    }

    public Integer getBizStatus(Integer orderStatus) {
        if (orderStatus == OrderStatus.refuse.getStatus().intValue()) {
            return 5;
        }
        if (orderStatus == OrderStatus.wait_auth.getStatus().intValue()) {
            return 3;
        } else if (orderStatus == OrderStatus.wait_loan.getStatus().intValue()) {
            return 4;
        } else if (orderStatus == OrderStatus.underway.getStatus().intValue()) {
            return 6;
        } else if (orderStatus == OrderStatus.refuse_loan.getStatus().intValue()) {
            return 7;
        }
        return 3;
    }

}
